package com.xiaoxu.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoxu.auth.service.SysMenuService;
import com.xiaoxu.auth.service.SysUserService;
import com.xiaoxu.common.exception.XiaoXuException;
import com.xiaoxu.common.jwt.JwtHelper;
import com.xiaoxu.common.result.Result;
import com.xiaoxu.common.utils.MD5;
import com.xiaoxu.model.system.SysUser;
import com.xiaoxu.vo.system.LoginVo;
import com.xiaoxu.vo.system.RouterVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;
    /**
     * 登录
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo) {
        SysUser sysUser = sysUserService.getByUsername(loginVo.getUsername());
        if(sysUser == null) {
            throw new XiaoXuException(201,"用户不存在");
        }
        if(!MD5.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())) {
            throw new XiaoXuException(201,"密码错误");
        }
        if(sysUser.getStatus().intValue() == 0) {
            throw new XiaoXuException(201,"用户被禁用");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", JwtHelper.createToken(sysUser.getId(), sysUser.getUsername()));
        return Result.ok(map);
    }
    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("info")
    public Result info(HttpServletRequest request) {

        //1.从请求头中获取信息 token
        String token = request.getHeader("token");
        //2.根据token 获取用户id
        Long userId = JwtHelper.getUserId(token);
        //3.查数据库,获取用户信息
        SysUser sysUser = sysUserService.getById(userId);
        //4.根据用户id 获取用户可以操作的菜单
        // 查询数据库,获取动态路由结构, 进行显示
         List<RouterVo> routerList =  sysMenuService.findUserMenuLisyByUserId(userId);
        //5.根据用户id,获取用户可以操作的按钮
         List<String > permsList = sysMenuService.findPermsByUserId(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("roles","[admin]");
        map.put("name",sysUser.getName());
        map.put("avatar","https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        map.put("routers",routerList);
        map.put("buttons",permsList);
        return Result.ok(map);
    }
    /**
     * 退出
     * @return
     */
    @PostMapping("logout")
    public Result logout(){
        return Result.ok();
    }

}
